package com.atguigu.tingshu.album.receiver;

import com.atguigu.tingshu.album.service.TrackInfoService;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.vo.album.TrackStatMqVo;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author: atguigu
 * @create: 2025-07-28 14:14
 */
@Slf4j
@Component
public class AlbumReceiver {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private TrackInfoService trackInfoService;

    /**
     * 监听更新声音/专辑统计信息
     *
     * @param mqVo
     * @param message
     * @param channel
     */
    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(value = MqConst.EXCHANGE_TRACK, durable = "true"),
            value = @Queue(value = MqConst.QUEUE_TRACK_STAT_UPDATE, durable = "true"),
            key = MqConst.ROUTING_TRACK_STAT_UPDATE
    ))
    public void updateStat(TrackStatMqVo mqVo, Message message, Channel channel) {
        if (mqVo != null) {
            log.info("更新声音/专辑统计信息：{}", mqVo);
            //1.幂等性处理
            //1.1 从MQ消息对象中获取消息唯一标识
            String key = RedisConstant.BUSINESS_PREFIX + "db:" + mqVo.getBusinessNo();
            //1.2 尝试采用set nx写入Redis
            Boolean flag = redisTemplate.opsForValue().setIfAbsent(key, "1", 5, TimeUnit.MINUTES);

            //1.3 写入成功消息才进行业务处理，写入失败（消息重复被MQ服务器投递）忽略消息
            if (flag) {
                //2.业务处理
                trackInfoService.updateStat(mqVo);

            }
        }
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }


}
